//聊天上下文
var contextarray = [];
//选中的文本
var selectedText='';
//上一次选中的文本
var lastSelectedText ='';
//ai对面框
var chat_html='';
//聊天容器
let jyy_chat_container ;
//聊天头部
let jyy_chat_header ;
//聊天容器坐标
let offsetX, offsetY;

//输入框
let textArea;
//发送消息按钮
let sendMessageButton;
//消息右边的容器
let  jyy_chat_message_content;
//创建ai交互按钮
let ai_button = document.createElement('img');
ai_button.src = 'icons/icon128.png';
document.body.appendChild(ai_button);
// 动态添加 CSS 样式
let ai_logo_style = document.createElement('style');
ai_logo_style.textContent = `
      .jyy-ai-logo {
        position: fixed;
        width:40px;
        height:40px;
        cursor: pointer;
        z-index: 99999;
        display: none;
      }
      .jyy-ai-logo:hover {
        transform: scale(1.3);  /* 放大效果 */
      }
    `;
document.head.appendChild(ai_logo_style);
// 给 logo 添加类
ai_button.classList.add('jyy-ai-logo');

// 监听鼠标松开事件
document.addEventListener('mouseup', () => {
    const selection = window.getSelection();
    //选中文本
    selectedText = selection.toString();

    // 如果有选中区域
    if (selectedText.length > 0 && selectedText !== lastSelectedText ) {
        lastSelectedText = selectedText;

        const range = selection.getRangeAt(0);
        const rect = range.getBoundingClientRect();

        // 设置按钮位置，显示按钮
        ai_button.style.left = `${rect.right + window.scrollX}px`; // 加上滚动偏移
        ai_button.style.top = `${rect.top + window.scrollY - 15}px`;  // 加上滚动偏移
        ai_button.style.display = 'block';
    } else {
        // 如果没有选中区域，隐藏按钮
        ai_button.style.display = 'none';
    }
});

// AI交互按钮点击事件
ai_button.addEventListener('click', () => {
    //隐藏ai交互按钮
    ai_button.style.display = 'none';

    let has_jyy_chat_container = document.querySelector('.jyy_chat_container');
    if(!has_jyy_chat_container){
        // 创建并添加对话框容器
        let chatDialog = document.createElement('div');
        chatDialog.classList.add('jyy_chat_container');
        chatDialog.style.display = 'block'; // 显示对话框
        chatDialog.style.position = 'fixed';
        chatDialog.style.top = '20%';
        chatDialog.style.left = '50%';
        chatDialog.style.transform = 'translateX(-50%)';
        chatDialog.style.backgroundColor = '#fff';
        chatDialog.style.border = '1px solid #ccc';
        chatDialog.style.boxShadow = '0px 4px 10px rgba(0, 0, 0, 0.1)';
        chatDialog.style.width = '598px';
        chatDialog.style.height = '428px';
        chatDialog.style.zIndex = '99999';
        chatDialog.style.borderRadius = '25px';

        //创建聊天界面
        chat_html= `
    <style>
        .jyy_chat_header {
            height: 30px;
            cursor: move;
            padding: 5px;
            border-bottom: 1px solid rgb(204, 204, 204);
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .jyy_chat_body {
            display: flex;
            height: 390px;
        }
        .jyy_chat_left_sidebar {
            width: 20%;
            border-right: 1px solid rgb(204, 204, 204);
        }
        .jyy_chat_left_sidebar h2 {
            text-align: center;
            font-size: 18px;
            /*border-bottom: 1px solid #dadada;*/
            padding-bottom: 10px;
        }
        .jyy_chat_left_sidebar ul {
            padding-left: 10px;
            list-style: none;
        }
        .jyy_chat_left_sidebar ul li {
            padding: 8px 0;
            font-size: 14px;
            color: #333;
            cursor: pointer;
            width: 100px;
        }
        .jyy_chat_left_sidebar ul li:hover {
            background-color: #e4e4e4;
        }
        .jyy_chat_right_content {
            width: 80%;
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
        .jyy_chat_textareaBox {
            width: 100%;
            max-width: 67%;
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            bottom: 10px;
            position: fixed;
        }
        .jyy_chat_textareaBox_input:focus {
            outline: none;
            border: none;
        }
        .jyy_chat_textareaBox_input {
            width: 90%;
            line-height: 20px;
            overflow-y: hidden;
            border: none;
            border-radius: 5px;
            resize: none;
            height: 20px;
            color: #666;
            font-size: 13px;
            padding-right: 30px;
            max-height: 80px;
        }
        .jyy_chat_send_icon {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            width: 25px;
            height: 25px;
        }
        .jyy_chat_message_content{
            width: 100%;
            position: fixed;
            top: 40px;
            height: 62%;
            padding: 15px;
            max-width: 67%;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }
        .jyy_chat_user_msg {
            padding: 10px;
            margin: 5px -10px 0 5px;
            border-radius: 10px;
            max-width: 80%;
            font-size: 10px;
        }
        .jyy_chat_user_msg.left {
            background-color: #f0f0f0;
            align-self: flex-start;
        }
        .jyy_chat_user_msg.right {
            background-color: #3167f2;
            color: white;
            align-self: flex-end;
        }
        .jyy_chat_message_content::-webkit-scrollbar {
          width: 0; /* 隐藏滚动条 */
          height: 0;
        }
        .jyy_chat_textareaBox_input::-webkit-scrollbar {
          width: 0; /* 隐藏滚动条 */
          height: 0;
        }
    </style>
    <div class="jyy_chat_header">
        <div style="display: flex; align-items: center;">
            <img src="icons/icon24.png">
            <span style="font-weight: bold;margin-left: 10px">DeepSeek AI</span>
        </div>
    </div>
    <div class="jyy_chat_body">
        <div class="jyy_chat_left_sidebar">
            <h2>会话记录</h2>
            <ul>
                <li>1+1为什么等...</li>
                <li>1+1为什么等...</li>
                <li>1+1为什么等...</li>
                <li>1+1为什么等...</li>
                <li>1+1为什么等...</li>
                <li>1+1为什么等...</li>
            </ul>
        </div>
        <div class="jyy_chat_right_content">
            <div class="jyy_chat_message_content">
            </div>
            <div class="jyy_chat_textareaBox">
                <textarea class="jyy_chat_textareaBox_input" placeholder="Shift+Enter换行、Enter发送"></textarea>
                <img src="send.png" alt="" class="jyy_chat_send_icon"> <!-- 图标 -->
            </div>
        </div>
    </div>
`;
        chatDialog.innerHTML=chat_html;

        // 将对话框添加到页面
        document.body.appendChild(chatDialog);
    }else{
        jyy_chat_container.style.display='block'
    }
    
    textArea = document.querySelector('.jyy_chat_textareaBox_input');

    //监听textArea输入
    textArea.addEventListener('input', function() {
        let value = textArea.value;
        let scrollHeight = textArea.scrollHeight;//完整高度
        let clientHeight = textArea.clientHeight; //可见高度
        let setHeihgt = (scrollHeight-4);
        textArea.style.height =setHeihgt+'px';
        if(value===''){
            textArea.style.height='20px';
            textArea.style.overflowY = 'hidden';
        }
        if(scrollHeight>84){
            textArea.style.overflowY = 'auto';
        }
    });

    // 监听textArea的keydown
    textArea.addEventListener('keydown', function(event) {
        if (event.key === 'Enter') {
            if (event.shiftKey) {
                let scrollHeight = textArea.scrollHeight;//完整高度
                let clientHeight = textArea.clientHeight; //可见高度
                let setHeihgt = (scrollHeight-4);
                textArea.style.height =setHeihgt+'px';
                if(textArea.scrollHeight>84){
                    textArea.style.overflowY = 'auto';
                }
            } else {
                event.preventDefault();
                sendMessageButton.click()
            }
        }
    });

    sendMessageButton=document.querySelector('.jyy_chat_send_icon');
    jyy_chat_message_content = document.querySelector('.jyy_chat_message_content');

    // 发送按钮-发送消息
    sendMessageButton.addEventListener('click', () => {
        // 如果已经点击过，则返回
        let message = textArea.value;
        if (message.trim()) {

            //聊天窗口显示消息
            show_msg(message,'right');

            //请求服务器
            send_requset(message)
        }
    });

    textArea.value = selectedText;
    sendMessageButton.click();

    jyy_chat_container = document.querySelector('.jyy_chat_container');
    jyy_chat_header = document.querySelector('.jyy_chat_header');

    //点击聊天对话框外部区域时，隐藏对话框
    document.addEventListener('click', (event) => {
        if (!jyy_chat_container.contains(event.target) && event.target !== ai_button) {
            jyy_chat_container.style.display = 'none'; // 隐藏对话框
        }
    });

    //拖拽
    draggable()
});

//聊天窗口显示消息
function show_msg(message,type='right'){
    // 创建新的消息元素
    let newMessage = document.createElement('div');
    newMessage.classList.add('jyy_chat_user_msg');
    newMessage.classList.add(type);
    newMessage.textContent = message;
    // 将新的消息添加到聊天容器的末尾
    jyy_chat_message_content.appendChild(newMessage);
    // 滚动到最新消息
    jyy_chat_message_content.scrollTop = jyy_chat_message_content.scrollHeight;
    // 清空输入框
    if(type==='right'){
        textArea.value = '';
        textArea.style.height='20px';
        textArea.style.overflowY = 'hidden';
    }
}

//拖拽
function draggable() {
    // 鼠标按下事件，记录鼠标位置
    jyy_chat_header.addEventListener('mousedown', (e) => {
        offsetX = e.clientX - jyy_chat_container.offsetLeft;
        offsetY = e.clientY - jyy_chat_container.offsetTop;

        // 设置鼠标移动事件
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', stopDrag);
    });
}

// 拖拽事件，更新 div 位置
function drag(e) {
    jyy_chat_container.style.left = `${e.clientX - offsetX}px`;
    jyy_chat_container.style.top = `${e.clientY - offsetY}px`;
}

// 停止拖拽事件，移除事件监听
function stopDrag() {
    document.removeEventListener('mousemove', drag);
    document.removeEventListener('mouseup', stopDrag);
}

// 请求服务器
function send_requset(message) {
    const xhr=new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                let resp = JSON.parse(xhr.responseText);
                if(resp.status){
                    streaming();
                }
            } else {
                console.error('Request failed with status: ' + xhr.status);
            }
        }
    };
    xhr.open('POST','https://hnjmlp.cn/ai/');
    xhr.setRequestHeader('Content-Type',"application/x-www-form-urlencoded");
    xhr.send('message='+message+'&context=[]');
}

function getCookie(name) {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();
        if (cookie.indexOf(name + '=') === 0) {
            return cookie.substring(name.length + 1, cookie.length);
        }
    }
    return null;
}

function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function streaming() {
    var es = new EventSource("https://hnjmlp.cn/ai/stream.php");
    var isstarted = true;
    var alltext = "";
    var isalltext = false;
    let err_msg='';
    es.onerror = function (event) {
        var errcode = getCookie("errcode");
        switch (errcode) {
            case "invalid_api_key":
                err_msg='API-KEY不合法';
                break;
            case "context_length_exceeded":
                err_msg='问题和上下文长度超限，请重新提问';
                break;
            case "rate_limit_reached":
                err_msg='同时访问用户过多，请稍后再试';
                break;
            case "access_terminated":
                err_msg='违规使用，API-KEY被封禁';
                break;
            case "no_api_key":
                err_msg='未提供API-KEY';
                break;
            case "insufficient_quota":
                err_msg='API-KEY余额不足';
                break;
            case "account_deactivated":
                err_msg='账户已禁用';
                break;
            case "model_overloaded":
                err_msg='模型超负荷，请重新发起请求';
                break;
            case null:
                err_msg='服务器访问超时或未知类型错误';
                break;
            default:
                err_msg='服务器故障，错误类型：'+ errcode;
        }
        es.close();
        show_msg(err_msg,'left');
        return;
    }
    es.onmessage = function (event) {
        if (isstarted) {
            // layer.close(loading);
            // $("#kw-target").val("请耐心等待AI把话说完……");
            // $("#kw-target").attr("disabled", true);
            // autoresize();
            // $("#ai-btn").html('<i class="iconfont icon-wuguan"></i>中止');
            // layer.msg("处理成功！");
            isstarted = false;
            answer = randomString(16);
            $("#article-wrapper").append('<li class="article-title" id="q' + answer + '"><pre>我：</pre></li>');
            for (var j = 0; j < prompt.length; j++) {
                $("#q" + answer).children('pre').text($("#q" + answer).children('pre').text() + prompt[j]);
            }
            $("#article-wrapper").append('<li class="article-content" id="' + answer + '"></li>');
            let str_ = '';
            let i = 0;
            timer = setInterval(() => {
                let newalltext = alltext;
                let islastletter = false;
                //有时服务器错误地返回\作为换行符，尤其是包含上下文的提问时，这行代码可以处理一下。
                if (newalltext.split("\n\n").length == newalltext.split("\n").length) {
                    newalltext = newalltext.replace(/\\n/g, '\n');
                }
                if (str_.length < newalltext.length) {
                    str_ += newalltext[i++];
                    strforcode = str_ + "_";
                    if ((str_.split("```").length % 2) == 0) strforcode += "\n```\n";
                } else {
                    if (isalltext) {
                        clearInterval(timer);
                        strforcode = str_;
                        islastletter = true;
                        $("#kw-target").val("");
                        $("#kw-target").attr("disabled", false);
                        // autoresize();
                        $("#ai-btn").html('<i class="iconfont icon-wuguan"></i>发送');
                        if (!isMobile()) $("#kw-target").focus();
                    }
                }
                newalltext = mdHtml.render(strforcode);
                $("#" + answer).html(newalltext);
                if (islastletter) MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
                $("#" + answer + " pre code").each(function () {
                    $(this).html("<button onclick='copycode(this);' class='codebutton'>复制</button>" + $(this).html());
                });
                document.getElementById("article-wrapper").scrollTop = 100000;
            }, 30);
        }
        if (event.data == "[DONE]") {
            isalltext = true;
            contextarray.push([_selectedText, alltext]);
            contextarray = contextarray.slice(-5); //只保留最近5次对话作为上下文，以免超过最大tokens限制
            es.close();
            return;
        }
        var json = eval("(" + event.data + ")");
        if (json.choices[0].delta.hasOwnProperty("content")) {
            if (alltext == "") {
                alltext = json.choices[0].delta.content.replace(/^\n+/, '');//去掉回复消息中偶尔开头就存在的连续换行符
            } else {
                alltext += json.choices[0].delta.content;
            }
        }
    }
}
